#include "formatters/json_formatter.hpp"
#include <chrono>
#include <iomanip>
#include <sstream>
#include <iostream>

std::string JsonFormatter::levelToString(LogLevel level) const {
    switch (level) {
        case LogLevel::Trace: return "TRACE";
        case LogLevel::Debug: return "DEBUG";
        case LogLevel::Info: return "INFO";
        case LogLevel::Warn: return "WARN";
        case LogLevel::Error: return "ERROR";
        case LogLevel::Critical: return "CRITICAL";
        case LogLevel::Off: return "OFF";
    } 
    return "UNKNOWN";
}


std::string JsonFormatter::format(const LogEntry& entry) const {
    nlohmann::json j;

    // 格式化时间戳
    auto in_time_t = std::chrono::system_clock::to_time_t(entry.timestamp);
    std::stringstream ss_time;
    ss_time << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %H:%M:%S");


    j["timestamp"] = ss_time.str();
    j["level"] = levelToString(entry.level);
    j["message"] = entry.message;

    j["thread_id"] = entry.thread_id;
    j["trace_id"] = entry.trace_id;
    j["span_id"] = entry.span_id;

    // 合并上下文数据
    if (!entry.context && !entry.context->empty()) {
        if (entry.context->is_object()) {
            j.update(*entry.context);
        } 
        else {
            std::cerr << "Warning: LogEntry context is not a JSON object, cannot update(). Adding as 'context_data' field." << std::endl;
             j["context_data"] = *entry.context;
        }
    }
    return j.dump();  // 转换成json数据
}
